<?php

namespace App\Models\Order;

use App\Models\Custom\Custom;
use Illuminate\Database\Eloquent\Model;

class Contractorder extends Model
{
    protected $table = 'contract_order';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     * 列表
     */
    public static function getList($request, $memberinfo, $isgetall)
    {
        $manger_id = $memberinfo['id'] ?? 0;
        $cpid = $memberinfo['cpid'] ?? 0;
        $utype = $memberinfo['utype']??0;
        // $sys_dpm_id = $memberinfo['sys_dpm_id'] ?? 0;

        $query = self::with('suborder')->with('custom_info')->orderBy('create_at', 'desc');
        //单据日期
        $start_time = $request->start_time;
        $end_time = $request->end_time;
        if($start_time && $end_time){
            $query->whereBetween('document_date', [$start_time, $end_time]);
        }

        //客户名称
        $custom_name = $request->custom_name;
        if ($custom_name != '') {
            $query->where('custom_name', 'like', '%' . $custom_name . '%');
        }

        //单据编号
        $document_number = $request->document_number;
        if ($document_number != '') {
            $query->where('document_number', 'like', '%' . $document_number . '%');
        }

        /**
         *  manger 1自己添加的数据，2所有数据
         *  销售只能看到自己的数据,2025.04.01
         *
         **/
        $manger = $request->manger;
        if ($manger == 1 || $utype == '7') {
            $query->where('manger_id', '=', $manger_id);
        }

        if ($cpid > 0) {
            $query->where('cpid', $cpid);
        }

        // if ($sys_dpm_id > 0) {
        //     $query->where('sys_dpm_id', $sys_dpm_id);
        // }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    /**
     * 详情
     */
    public static function getone($id)
    {
        return self::with('suborder')->with('custom_info')->where('id', $id)->get();
    }

    /**
     * 获取子订单
     */
    public function suborder()
    {
        return $this->hasMany(Contractordersub::class, 'p_id', 'id');
    }

    public function custom_info()
    {
        return $this->hasOne(Custom::class, 'id', 'custom_id');
    }
}
